import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message, Select, Switch, Row, Col, Card } from 'antd';
import { createUnit, getApplicationList, getUnitsByAppId, getUnitDetails } from '../../services/unit';

interface AddUnitModalProps {
    visible: boolean;
    onCancel: () => void;
    onSuccess: () => void;
}

const { Option } = Select;

interface ApplicationInfo {
    appId: string;
    appName: string;
}

interface BusinessUnitInfo {
    unitId: string;
    unitNameCn: string;
    firstUnitType: string;
    secondUnitType: string;
    thirdUnitType: string;
    gitlabGroup: string;
    gitlabProject: string;
    gitlabProjectId: string;
    gitlabProjectUrl: string;
    appId: string;
    appName: string;
    teamName: string;
}

const AddUnitModal: React.FC<AddUnitModalProps> = ({ visible, onCancel, onSuccess }) => {
    const [form] = Form.useForm();
    const [applications, setApplications] = useState<ApplicationInfo[]>([]);
    const [units, setUnits] = useState<BusinessUnitInfo[]>([]);
    const [selectedUnit, setSelectedUnit] = useState<BusinessUnitInfo | null>(null);
    const [loading, setLoading] = useState(false);

    // 加载应用列表
    useEffect(() => {
        if (visible) {
            loadApplications();
            // 设置功能开关和过滤规则的默认值
            form.setFieldsValue({
                // 功能开关默认值（按任务顺序）- 新建单元默认开启所有分析
                jarTask: true, // 源码分析默认开启且不可关闭
                gitTask: true, // 变更记录分析默认开启
                statisticsTask: true, // 统计分析默认开启
                apmTask: true, // APM分析默认开启
                saTask: true,  // SA分析默认开启
                deprecationAnalysisTask: true, // 废弃分析默认开启
                // 包过滤规则默认值为空（不限制）
                packageRuleReg: '',
                packageRuleExclude: '',
                // JAR过滤规则默认值为空
                jarNameFilter: '',
                jarExcludeFilter: ''
            });
        }
    }, [visible]);

    const loadApplications = async () => {
        try {
            const response = await getApplicationList();
            if (response?.data) {
                setApplications(response.data);
            }
        } catch (error) {
            message.error('加载应用列表失败');
        }
    };

    // 应用选择变化
    const handleAppChange = async (appId: string) => {
        form.setFieldsValue({ unitId: undefined });
        setSelectedUnit(null);
        setUnits([]);

        try {
            const response = await getUnitsByAppId(appId);
            if (response?.data) {
                setUnits(response.data);
            }
        } catch (error) {
            message.error('加载单元列表失败');
        }
    };

    // 单元选择变化
    const handleUnitChange = async (unitId: string) => {
        try {
            const response = await getUnitDetails(unitId);
            if (response?.data) {
                setSelectedUnit(response.data);
                // 自动填充表单字段
                form.setFieldsValue({
                    artifactoryPath: '', // 制品路径为空，需要用户填写
                    unitType: `${response.data.firstUnitType}/${response.data.secondUnitType}/${response.data.thirdUnitType}`,
                    ownTeam: response.data.teamName,
                    gitRepoUrl: response.data.gitlabProjectUrl,
                    // 设置过滤规则默认值为空（不限制）
                    packageRuleReg: '',
                    packageRuleExclude: '',
                    jarNameFilter: '',
                    jarExcludeFilter: '',
                    // 保持功能开关的现有值不变（按任务顺序），确保源码分析始终开启
                    jarTask: true, // 源码分析强制开启
                    gitTask: form.getFieldValue('gitTask'),
                    statisticsTask: form.getFieldValue('statisticsTask'),
                    apmTask: form.getFieldValue('apmTask'),
                    saTask: form.getFieldValue('saTask'),
                    deprecationAnalysisTask: form.getFieldValue('deprecationAnalysisTask') // 废弃分析保持现有值
                });
            }
        } catch (error) {
            message.error('加载单元详情失败');
        }
    };

    const handleOk = async () => {
        try {
            setLoading(true);
            const values = await form.validateFields();
            await createUnit(values);
            message.success('新建单元成功');
            form.resetFields();
            setApplications([]);
            setUnits([]);
            setSelectedUnit(null);
            onSuccess();
        } catch (err: any) {
            message.error(err?.response?.data?.msg || '新建失败');
        } finally {
            setLoading(false);
        }
    };

    const handleCancel = () => {
        form.resetFields();
        setApplications([]);
        setUnits([]);
        setSelectedUnit(null);
        onCancel();
    };

    return (
        <Modal
            title="新建单元"
            open={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            confirmLoading={loading}
            destroyOnClose
            width={900}
            style={{ top: 20 }}
            okText="确定"
            cancelText="取消"
        >
            <Form form={form} layout="vertical" style={{ marginBottom: 0 }}>
                <Row gutter={[16, 8]}>
                    <Col span={12}>
                        <Form.Item
                            label="选择应用"
                            name="appId"
                            rules={[{ required: true, message: '请选择应用' }]}
                            style={{ marginBottom: 8 }}
                        >
                            <Select
                                size="small"
                                placeholder="请选择应用"
                                onChange={handleAppChange}
                                showSearch
                                optionFilterProp="children"
                            >
                                {applications.map(app => (
                                    <Option key={app.appId} value={app.appId}>
                                        {app.appId} - {app.appName}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="选择单元"
                            name="unitId"
                            rules={[{ required: true, message: '请选择单元' }]}
                            style={{ marginBottom: 8 }}
                        >
                            <Select
                                size="small"
                                placeholder="请先选择应用"
                                onChange={handleUnitChange}
                                disabled={units.length === 0}
                                showSearch
                                optionFilterProp="children"
                            >
                                {units.map(unit => (
                                    <Option key={unit.unitId} value={unit.unitId}>
                                        {unit.unitId}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>

                {/* 单元详情展示 */}
                {selectedUnit && (
                    <div style={{ marginBottom: 8, padding: 6, background: '#f5f5f5', borderRadius: 4, fontSize: '11px', color: '#666' }}>
                        已选择单元：{selectedUnit.unitId}
                    </div>
                )}

                <Row gutter={[16, 8]}>
                    <Col span={12}>
                        <Form.Item
                            label="制品路径"
                            name="artifactoryPath"
                            style={{ marginBottom: 8 }}
                        >
                            <Input size="small" placeholder="制品路径（可选）" />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="单元类型"
                            name="unitType"
                            rules={[{ required: true, message: '请选择单元类型' }]}
                            style={{ marginBottom: 8 }}
                        >
                            <Input size="small" placeholder="选择单元后自动填充" disabled={!!selectedUnit} />
                        </Form.Item>
                    </Col>
                </Row>

                <Row gutter={[16, 8]}>
                    <Col span={24}>
                        <Form.Item
                            label="开发团队"
                            name="ownTeam"
                            rules={[{ required: true, message: '请输入开发团队' }]}
                            style={{ marginBottom: 8 }}
                        >
                            <Input size="small" disabled={!!selectedUnit} />
                        </Form.Item>
                    </Col>
                </Row>

                <Row gutter={[16, 8]}>
                    <Col span={24}>
                        <Form.Item
                            label="git仓库地址"
                            name="gitRepoUrl"
                            rules={[{ required: true, message: '请输入git仓库地址' }]}
                            style={{ marginBottom: 8 }}
                        >
                            <Input size="small" disabled={!!selectedUnit} />
                        </Form.Item>
                    </Col>
                </Row>

                {/* 功能开关 */}
                <Card
                    title="功能开关"
                    size="small"
                    style={{ marginBottom: 12 }}
                    headStyle={{
                        backgroundColor: '#f0f9ff',
                        borderBottom: '2px solid #10b981',
                        fontSize: '13px',
                        fontWeight: 'bold',
                        padding: '8px 16px',
                        minHeight: '32px'
                    }}
                    bodyStyle={{ padding: '12px 16px' }}
                >
                    <div style={{ color: '#666', fontSize: '11px', marginBottom: 8 }}>
                        启用或禁用不同类型的代码分析任务
                    </div>
                    <Row gutter={[12, 6]}>
                        <Col span={4}>
                            <Form.Item
                                name="jarTask"
                                label="源码分析"
                                valuePropName="checked"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '11px' } }}
                            >
                                <Switch
                                    size="small"
                                    checkedChildren="开"
                                    unCheckedChildren="关"
                                    disabled={true}
                                    defaultChecked={true}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Form.Item
                                name="gitTask"
                                label="变更记录分析"
                                valuePropName="checked"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '11px' } }}
                            >
                                <Switch
                                    size="small"
                                    checkedChildren="开"
                                    unCheckedChildren="关"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Form.Item
                                name="statisticsTask"
                                label="统计分析"
                                valuePropName="checked"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '11px' } }}
                            >
                                <Switch
                                    size="small"
                                    checkedChildren="开"
                                    unCheckedChildren="关"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Form.Item
                                name="apmTask"
                                label="APM分析"
                                valuePropName="checked"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '11px' } }}
                            >
                                <Switch
                                    size="small"
                                    checkedChildren="开"
                                    unCheckedChildren="关"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Form.Item
                                name="saTask"
                                label="SA分析"
                                valuePropName="checked"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '11px' } }}
                            >
                                <Switch
                                    size="small"
                                    checkedChildren="开"
                                    unCheckedChildren="关"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Form.Item
                                name="deprecationAnalysisTask"
                                label="废弃分析"
                                valuePropName="checked"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '11px' } }}
                            >
                                <Switch
                                    size="small"
                                    checkedChildren="开"
                                    unCheckedChildren="关"
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                </Card>

                {/* 过滤规则配置 */}
                <Card
                    title="过滤规则配置"
                    size="small"
                    style={{ marginBottom: 8 }}
                    headStyle={{
                        backgroundColor: '#f0f9ff',
                        borderBottom: '2px solid #3b82f6',
                        fontSize: '13px',
                        fontWeight: 'bold',
                        padding: '6px 16px',
                        minHeight: '28px'
                    }}
                    bodyStyle={{ padding: '8px 16px' }}
                >
                    <div style={{ color: '#666', fontSize: '11px', marginBottom: 6 }}>
                        配置包过滤和JAR过滤规则，控制代码分析范围（留空表示不限制）
                    </div>
                    <Row gutter={[12, 6]}>
                        <Col span={12}>
                            <Form.Item
                                label="包名白名单（Include）"
                                name="packageRuleReg"
                                style={{ marginBottom: 6 }}
                                labelCol={{ style: { fontSize: '12px' } }}
                                tooltip="指定要分析的包，支持前缀匹配（com.example）、关键词匹配（*devops*），多个用逗号分隔"
                            >
                                <Input.TextArea
                                    size="small"
                                    rows={2}
                                    placeholder="例: com.example,org.myproject 或 *devops*"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="包名黑名单（Exclude）"
                                name="packageRuleExclude"
                                style={{ marginBottom: 6 }}
                                labelCol={{ style: { fontSize: '12px' } }}
                                tooltip="指定要排除的包，支持前缀匹配和通配符，多个用逗号分隔"
                            >
                                <Input.TextArea
                                    size="small"
                                    rows={2}
                                    placeholder="例: *test*,*mock*,com.example.legacy"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="JAR文件白名单"
                                name="jarNameFilter"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '12px' } }}
                                tooltip="指定要分析的JAR文件名关键词，多个用逗号分隔"
                            >
                                <Input
                                    size="small"
                                    placeholder="例: myapp-,-service-"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="JAR文件黑名单"
                                name="jarExcludeFilter"
                                style={{ marginBottom: 0 }}
                                labelCol={{ style: { fontSize: '12px' } }}
                                tooltip="指定要排除的JAR文件名关键词，多个用逗号分隔"
                            >
                                <Input
                                    size="small"
                                    placeholder="例: -test-,-sources-,-javadoc-"
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                </Card>
            </Form>
        </Modal>
    );
};

export default AddUnitModal; 